package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.model.*;
import com.zzzyh.forumsystemclient.services.IArticleService;
import com.zzzyh.forumsystemclient.services.ICommentService;
import com.zzzyh.forumsystemclient.services.INotificationService;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.utils.IpUtil;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@Slf4j
public class CommentController {
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private INotificationService notificationService;

    @RequestMapping("/api/comment/list")
    public AppResult<PageResult<Comment>> list(@RequestParam int pageNum, @RequestParam int pageSize,
                                               @RequestParam Long articleId) {
        List<Comment> comments = commentService.list(pageNum, pageSize, articleId);
        for (Comment comment : comments){
            User user = userService.getUserinfoByUserId(comment.getUserId());
            comment.setNickname(user.getNickname());
            comment.setAvatar(user.getAvatar());
            if (comment.getReplyUserId() != null){
                User replyUser = userService.getUserinfoByUserId(comment.getReplyUserId());
                comment.setReplyNickname(replyUser.getNickname());
            }
        }
        List<Comment> commentTree = buildCommentTree(comments);
        Integer total = commentService.total(articleId);
        return AppResult.success(new PageResult<>(pageNum, pageSize,total , commentTree));
    }

    @RequestMapping("/api/comment/add")
    public AppResult<String> add(@RequestBody Comment comment,
                                 @RequestHeader("Authorization") String token,
                                 HttpServletRequest  request) {
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        comment.setUserId(userId);
        comment.setIp(IpUtil.getIp(request));;
        comment.setSystem(IpUtil.getOsName( request));
        comment.setBrowser(IpUtil.getUserAgent(request).getBrowser().toString());
        comment.setIpSource(IpUtil.getCityInfo(comment.getIp()));
        log.info("添加留言：{}", comment);
        commentService.add(comment);
        Notifications notifications = new Notifications();
        Article byArticleId = articleService.getByArticleId(comment.getArticleId());
        notifications.setUserId(Long.valueOf(byArticleId.getUserId()));
        notifications.setFromUserId(Long.valueOf(userId));
        notifications.setType("comment");
        notifications.setTitle("评论");
        notifications.setArticleId(comment.getArticleId());
        notifications.setIsRead(false);
        notifications.setMessage(comment.getContent());
        notifications.setCreateTime(new Date());
        notificationService.add(notifications);
        return AppResult.success("添加成功");
    }

    public List<Comment> buildCommentTree(List<Comment> comments) {
        if (comments == null || comments.isEmpty()) {
            return Collections.emptyList();
        }

        // 将所有评论放入 map，便于查找父子关系
        Map<Integer, Comment> commentMap = new HashMap<>();
        comments.forEach(comment -> commentMap.put(comment.getId(), comment));

        // 构建根评论和子评论的关系
        List<Comment> rootComments = new ArrayList<>();

        for (Comment comment : comments) {
            if (comment.getParentId() == null || comment.getParentId() == 0) {
                // 根评论
                rootComments.add(comment);
            } else {
                // 子评论，尝试找到父评论并加入其 children 列表
                Comment parent = commentMap.get(comment.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(comment);
                }
            }
        }

        return rootComments;
    }

    @RequestMapping("/protal/user/delMyComment/{commentId}")
    public AppResult<String> delMyComment(@PathVariable("commentId") Integer commentId){
        commentService.delMyComment(commentId);
        return AppResult.success("删除成功");
    }


}
